$(function () {
    //等待加载效果
    loading();

    ajaxbasicInfo();

    flushUser();

    $('#keyAD form input').blur(function () {
        var this_ = this;
        validateAD_Key(this_);
    });

    $('#ad_category_ul li').click(function () {
        ss($(this).val());
    });

    $('#hobby_ul li').click(function () {
        kk($(this).val());
    });

});

/**
 * 加载基本信息页面所需用户信息
 */
function ajaxbasicInfo() {

    var url = "/Lvscore_User_M/account/ajaxbasicInfo";
    $.post(url, function (data) {

        //基本信息 ========================
        $("#user_id_").text(data.devId);
        $("#username_").val(data.name);
        var s = data.tel_num;
        $("#tel_num_").text(s.substring(0, 3) + "-" + s.substring(3, 7) + "-" + s.substring(7, 11));

        if (data.mail == null || data.mail == 'null' || data.mail == '')
            $("#email_").html(
                '<input type="text" placeholder="请输入新的邮箱" style="width:40%;margin-left:-12px;height:40px;margin-bottom:10px;" class="border" id="mail" onmousedown="getnewMailDiv()" onkeyup="getnewMailDiv()" name="mail"/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;' +
                '<input type="button" id="getcode" style="display: none ;width:100px;height:30px;text-align:center;background:#ccc;border-radius:3px;border:1px solid #333;" class="inline-block handes" onclick="getCodeToNewMail(this)" value="获取验证码"/><br/>' +
                '<div id="newMail_Div" style="display: none">' +
                '<label class="label">填写验证码&nbsp;:</label> ' +
                '<input type="text" placeholder="请填写验证码" class="border" style="width:24%;height:40px;margin-left:8px;" id="code" name="code"/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;' +
                '<input type="button" style="width:100px;height:30px;text-align:center;background:#ccc;border-radius:3px;border:1px solid #333;" class="inline-block handes" onclick="bandingMail(this)" value="绑定邮箱"/>' +
                '</div>'
            );
        else
            $("#email_").append(data.mail + '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;' +
                '<A href="javascript:changeMail()" id="changeMail_A" style="color:gray;font-size: 14px; display: none">更改邮箱</A>');

        //详细信息 ==========================
        if (isNotEmpty(data.real_name)) {
            $("#real_name_span").text(data.real_name);
        } else {
            $("#real_name_span").append('<input type="text" id="real_name" onkeyup="getCredentials_Box()" onblur="validateRealName()" style="width:130px;height:31px;line-height:31px;padding-left: 1px;"/><span id="real_name_validate"></span><br/>' +
                '<label id="credentials_lab" style="display: none" class="label">证件：</label><span id="credentials_span" style="display: none"></span><input type="hidden" id="real_name_null_flag" value="1"/>');//' + data.devId + '
            $("#credentials_span").html('&nbsp;' +
                '<select name="" class="common1" id="credentialsType" onchange="validateCredentials()" style="width:90px;">' +
                '<option value="0">身份证</option>' +
                '<option value="1">护照</option>' +
                '<option value="2">军官证</option>' +
                '</select>&nbsp;&nbsp;&nbsp;' +
                '<input id="credentialsNum" type="text" disabled="disabled" onblur="validateCredentials()" style="width:180px;height:31px;line-height:31px;margin-top: 10px;padding-left: 1px;" class="border"/>' +
                '<span id="credentials_validate"></span>'
            );
        }
        if (isNotEmpty(data.sex)) {
            $("#user_sex").text(getSex(data.sex));
            $("#user_sex").append('<input type="hidden" id="sexStatus" value="' + data.sex + '"/>');
        } else
            $("#user_sex").html(
                '<input type="radio" value="0" name="user_sex" id="man"/> <label for="man"> 男</label> ' +
                '<input type="radio" value="1" name="user_sex" id="woman"/> <label for="woman"> 女</label><input type="hidden" id="sex_null_flag" value="1"/>'
            );
        $("[name='user_age'] option").each(function () {
            if (data.birth == $(this).val()) {
                $(this).attr("selected", true);
            }
        });
        $("[name='user_education'] option").each(function () {
            if (data.education == $(this).val()) {
                $(this).attr("selected", true);
            }
        });
        $("[name='marital_status'][value='" + data.marital_status + "']").attr("checked", true);
        $("[name='children'][value='" + data.children + "']").attr("checked", true);
        distpicker(data.area); //地区显示
        $("[name='house'][value='" + data.house + "']").attr("checked", true);
        $("[name='car'][value='" + data.car + "']").attr("checked", true);
        $("[name='m_income'] option").each(function () {
            if (data.monthly_income == $(this).val()) {
                $(this).attr("selected", true);
            }
        });

        //广告类型 ==========================
        var ys_ad_category = data.ad_category;
        if (isNotEmpty(ys_ad_category)) {
            var ad_category = ys_ad_category.split("|");
            for (var i = 0; i < ad_category.length; i++) {
                if (ad_category[i] != '') {
                    ss(Number(ad_category[i]), '1');
                }
            }
        }

        //广告需求关键字 ====================
        var ys_ad_key = data.ad_key;
        if (isNotEmpty(ys_ad_key)) {
            ys_ad_key = ys_ad_key.substring(1); //为适配安卓部分 进行调整
            var ad_key = ys_ad_key.split("|");
            for (var i = 0; i < ad_key.length; i++) {
                if (ad_key[i] != '') {
                    document.getElementById("ad_key" + (i + 1)).value = ad_key[i];
                }
            }
        }

        //兴趣爱好 ==========================
        var ys_hobby = data.hobby;
        if (isNotEmpty(ys_hobby)) {
            var hobby = ys_hobby.split("|");
            for (var i = 0; i < hobby.length; i++) {
                if (hobby[i] != '') {
                    kk(Number(hobby[i]), '1');
                }
            }
        }

        disableOcx(0);
        disableOcx(1);
        disableOcx(2);
        disableOcx(3);
        disableOcx(4);

        //等待加载的效果消失
        $(".loadingBox").hide();

    }, "json");
}
/**
 * 三级联动
 * @param area
 */
function distpicker(area) {
    //三级联动的默认样式
    var $distpicker = $("#user_area");

    if (!isNotEmpty(area) || area == '--') {
        $distpicker.distpicker({
            autoSelect: false
        });
    } else {
        var areas = area.split("-");
        $distpicker.distpicker({
            province: areas[0],
            city: areas[1],
            district: areas[2]
        });
        //地区三级联动
        $distpicker.distpicker({
            autoSelect: true
        });
    }
}

function getSex(sex) {
    if (sex == '0')
        return '男';
    else if (sex == '1')
        return '女';
    else
        return sex;
}

function getCodeToNewMail(that) {
    var mail = $("[name='mail']").val().trim();
    if (mail == null || mail == '') {
        alertBox("请填写邮箱", '');
    } else if (!isEmail(mail)) {
        alertBox("请按正确格式填写邮箱", '');
    } else {
        //settime(that);
        that.disabled = true;
        $(this).val("发送中...");
        ajaxGetCodeByNewMail(mail, that);
    }
}

function bandingMail(that) {
    var code = $("[name='code']").val().trim();
    var mail = $("[name='mail']").val().trim();
    if (mail == null || mail == '')
        alertBox("请填写邮箱", '');
    else if (!isEmail(mail))
        alertBox("请按正确格式填写邮箱", '');
    else if (!isNotEmpty(code))
        alertBox("请填写验证码", '');
    else {
        that.disabled = true;
        ajaxValidateCodeNewMail(that, mail, code);
    }
}

function changePhone() {
    window.location.href = "/Lvscore_User_M/userWeb/views/accounterCenter/oldTel.html";		// 修改手机页面
}
function getnewMailDiv() {
    if ($("#mail").val().trim() != '') {
        if ($("#mail").val().trim().length >= 1) {
            $("#newMail_Div").show();
            $("#getcode").show();
        }
    } else {
        $("#newMail_Div").hide();
        $("#getcode").hide();
    }
}

function changeMail() {
    window.location.href = "/Lvscore_User_M/userWeb/views/accounterCenter/oldEmail.html";	// 修改邮箱页面
}

// 控制是否可以编辑
// 使页面不可编辑
function disableOcx(iform) {
    var form = document.forms[iform];
    for (var i = 0; i < form.length; i++) {
        var element = form.elements[i];
        // 部分元素可以编号 element.name 是元素自定义 name
        if (element.name != "auditEntity.auditContent"
            && element.name != "auditEntity.auditAutograph"
            && element.name != "auditEntity.auditTime"
            && element.name != "auditEntity.auditState"
            && element.name != "submitBtn" && element.name != "reset"
            && element.name != "id" && element.name != "processInstanceId"
            && element.name != "updateForm") {
            element.disabled = "true";
        }
    }
}

// 取消不可编辑
function noDisable(iform) {
    var form = document.forms[iform];
    for (var i = 0; i < form.length; i++) {
        var element = form.elements[i];
        element.disabled = false;
    }
}

//基本信息修改
function updateone(iform) {
    if ($("input[name='onebtn']").attr("value") == "保存") {
        $('#changeMail_A').hide();
        $('#changeTel_A').hide();
        var username = $("#username_").val().trim();
        if (username == '' || username.length == 0) {
            alertBox("请输入用户名", "");
        }
        else if (!isName(username)) {
            alertBox("用户名不合法");
        }
        else {
            if (isNotEmpty($('#mail').val())) {
                $('#mail').val('');
                $("#newMail_Div").hide();
                $("#getcode").hide();
            }
            disableOcx(iform);
            $("input[name='onebtn']").attr("value", "修改");
            ajaxupdateone();
        }
    } else if ($("input[name='onebtn']").attr("value") == "修改") {

        $('#changeMail_A').show();
        $('#changeTel_A').show();
        noDisable(iform);
        $("input[name='onebtn']").attr("value", "保存");
    }
}
function ajaxupdateone() {
    var username = $("#username_").val();
    ajaxUpdateBasic(username);
}

//详细信息修改
function updatetwo(iform) {
    if ($("input[name='twobtn']").attr("value") == "保存") {
        if (ajaxupdatetwo()) {
            disableOcx(iform);
            $("input[name='twobtn']").attr("value", "修改");
        }
    } else if ($("input[name='twobtn']").attr("value") == "修改") {
        noDisable(iform);
        $("input[name='twobtn']").attr("value", "保存");
    }
}
function ajaxupdatetwo() {
    var real_name = $('#real_name').val();
    var credentials_type = $('#credentialsType').val();
    var credentials_num = $('#credentialsNum').val();
    var sex = $("[name='user_sex']:checked").val();
    var birth = $("[name='user_age']").val();
    var education = $("[name='user_education']").val();
    var marital_status = $("input[name='marital_status']:checked").val();
    var children = $("input[name='children']:checked").val();

    var prov = $("#province9 option:selected").val();
    var homecity = $("#city9 option:selected").val();
    var district = $("#district9 option:selected").val();
    var area = prov + '-' + homecity + '-' + district;

    var house = $("input[name='house']:checked").val();
    var car = $("input[name='car']:checked").val();

    var monthly_income = $("[name='m_income']").val();
    if (!(isNotEmpty(birth) && isNotEmpty(education) && isNotEmpty(marital_status) && isNotEmpty(children) && isNotEmpty(prov) && isNotEmpty(house) && isNotEmpty(monthly_income && ($('#sex_null_flag').val() == 1) ? isNotEmpty(sex) : true))) {
        alertBox('不能有未填项', '');
        return false;
    }
    var annual_income = monthly_income * 12;
    if (!isNotEmpty(sex)) {
        var sexs = $("#sexStatus").val();
        sex = isNotEmpty(sexs) ? sexs : null;
    }
    if (($('#real_name_null_flag').val() == 1) ? (validateRealName() && validateCredentials()) : true) {
        ajaxUpdateDetails(real_name, sex, birth, education, marital_status, children, car, area, house, credentials_type, credentials_num, monthly_income, annual_income, $('#real_name_null_flag').val());
    }
    return ($('#real_name_null_flag').val() == 1) ? (validateRealName() && validateCredentials()) : true;
}

//修改广告类型
function updatethree(iform) {
    if ($("input[name='threebtn']").attr("value") == "保存") {
        disableOcx(iform);
        $("input[name='threebtn']").attr("value", "修改");
        ajaxupdatethree();
        $(".contBox").disabled = true;
    } else if ($("input[name='threebtn']").attr("value") == "修改") {
        noDisable(iform);
        $("input[name='threebtn']").attr("value", "保存");
    }
}

function ajaxupdatethree() {
    var ul = document.getElementById("ad_category_ul").getElementsByTagName("li");
    var ad_category = '';
    for (var i = 0; i < ul.length; i++) {
        if (ul[i].className == 'active') {
            if (ad_category.length == 0) {
                ad_category = "|" + ul[i].value;
            } else {
                ad_category = ad_category + '|' + ul[i].value;
            }
        }
    }
    ajaxUpdateCategory(ad_category);
}

//修改广告分类关键字
function updatefour(iform) {
    if ($("input[name='fourbtn']").attr("value") == "保存") {
        if (validateAD_Key()) {
            disableOcx(iform);
            $("input[name='fourbtn']").attr("value", "修改");
            ajaxupdatefour();
        }
    } else if ($("input[name='fourbtn']").attr("value") == "修改") {
        noDisable(iform);
        $("input[name='fourbtn']").attr("value", "保存");
    }
}
function ajaxupdatefour() {
    var ad_key1 = document.getElementById("ad_key1").value;
    var ad_key2 = document.getElementById("ad_key2").value;
    var ad_key3 = document.getElementById("ad_key3").value;
    var ad_key4 = document.getElementById("ad_key4").value;
    var ad_key5 = document.getElementById("ad_key5").value;
    var ad_key6 = document.getElementById("ad_key6").value;
    var ad_key = '|' + ad_key1 + '|' + ad_key2 + '|' + ad_key3 + '|' + ad_key4 + '|' + ad_key5 + '|' + ad_key6;
    ajaxUpdateAd_key(ad_key);
}

//修改兴趣爱好
function updatefive(iform) {
    if ($("input[name='fivebtn']").attr("value") == "保存") {
        disableOcx(iform);
        $("input[name='fivebtn']").attr("value", "修改");
        ajaxupdatefive();
    } else if ($("input[name='fivebtn']").attr("value") == "修改") {
        noDisable(iform);
        $("input[name='fivebtn']").attr("value", "保存");
    }

}
function ajaxupdatefive() {
    var ul = document.getElementById("hobby_ul").getElementsByTagName("li");
    var hobby = '';
    for (var i = 0; i < ul.length; i++) {
        if (ul[i].className == 'active') {
            if (hobby.length == 0) {
                hobby = "|" + ul[i].value;
            } else {
                hobby = hobby + '|' + ul[i].value;
            }
        }
    }
    ajaxUpdateHobby(hobby);
}

//广告类型
function ss(index, flag) {
    if ($("input[name='threebtn']").attr("value") == "保存" || flag == '1') {
        if ($(".genreBox li").eq(index - 1000).attr("class") == '') {
            $(".genreBox li").eq(index - 1000).addClass("active").siblings();
            var src = "/Lvscore_User_M/userWeb/static/images/genres_pic" + index + ".png";
            $(".genreBox li img").eq(index - 1000).attr("src", src);
        } else if ($(".genreBox li").eq(index - 1000).attr("class") == 'active') {
            $(".genreBox li").eq(index - 1000).removeClass("active");
            var src1 = "/Lvscore_User_M/userWeb/static/images/genre_pic" + index + ".png";
            $(".genreBox li img").eq(index - 1000).attr("src", src1);
        }
    }
}

//兴趣爱好
function kk(index, flag) {

    if ($("input[name='fivebtn']").attr("value") == "保存" || flag == '1') {
        if ($(".interests li").eq(index - 1000).attr("class") == '') {
            $(".interests li").eq(index - 1000).addClass("active").siblings();
            var src = "/Lvscore_User_M/userWeb/static/images/interests_pic" + index + ".png";
            $(".interests li img").eq(index - 1000).attr("src", src);
        } else if ($(".interests li").eq(index - 1000).attr("class") == 'active') {
            $(".interests li").eq(index - 1000).removeClass("active");
            var src1 = "/Lvscore_User_M/userWeb/static/images/interest_pic" + index + ".png";
            $(".interests li img").eq(index - 1000).attr("src", src1);
        }
    }
}

function getCredentials_Box() {
    if ($("#real_name").val().trim() != '') {
        if ($("#real_name").val().trim().length >= 1) {
            $("#credentials_lab").show();
            $("#credentials_span").show();
        }
    } else {
        $("#credentials_lab").hide();
        $("#credentials_span").hide();
    }
}

/**
 * 校验证件类型和号码
 * @returns {boolean}
 */
function validateCredentials() {
    var credentialsType = $('#credentialsType').val();
    var credentialsNum = $('#credentialsNum').val();
    if (isNotEmpty(credentialsType)) {
        if (isNotEmpty(isCredentials(credentialsType, credentialsNum))) { //证件校验 返回空 则验证通过
            validateSpanMsg('credentials_validate', isCredentials(credentialsType, credentialsNum));
            return false;
        }
        else {
            validateSpanMsg('credentials_validate');
            return true;
        }
    } else {
        validateSpanMsg('credentials_validate', '证件号码不能为空');
        return false;
    }
}

/**
 * 校验用户名
 * @returns {boolean}
 */
function validateRealName() {
    if (isNotEmpty($('#real_name').val())) {
        validateSpanMsg('real_name_validate', '');
        if (isRealName($('#real_name').val())) {
            validateSpanMsg('real_name_validate', '');
            return true;
        } else {
            validateSpanMsg('real_name_validate', '姓名格式错误');
            return false;
        }
    } else {
        validateSpanMsg('real_name_validate', '姓名不能为空');
        return false;
    }
}

/**
 * 校验广告关键字  数字字母20个  汉字10个
 * @param that
 * @returns {boolean}
 */
function validateAD_Key(that) {
    if (that) {
        var info = that.value;
        if (getLength(info) > 20) {
            alertBox('您输入的长度超出限制', '');
            return false;
        } else {
            return true;
        }
    } else {
        var flag = true;
        $.each($('#keyAD form input'), function (i, e) {
            if (!validateAD_Key(e)) {
                flag = false;
                e.focus().select();
                return;
            }
        });
        if (!flag) {
            alertBox('存在不合法的关键字，请检查', '')
        }
        return flag;
    }
}

/**
 * 更新用户基本信息
 *
 * @param name
 *            (用户名 name)
 */
function ajaxUpdateBasic(name) {
    var url = "/Lvscore_User_M/account/ajaxUpdateBasic";
    $.post(url, {
        'name': name
    }, function (data) {
        if (data == '1') {
            flushUser();//更新cookie中的user
            alertBox("修改成功");
        }
        else if (data == '-1')
            alertBox("修改失败", '');
        else
            alertBox("服务器异常", '');
    }, "json");
}

/**
 * 更新用户详细信息
 *
 * @param birth
 * @param education
 * @param marital_status
 * @param children
 * @param car
 * @param area
 * @param house
 * @param monthly_income
 * @param annual_income
 */
function ajaxUpdateDetails(real_name, sex, birth, education, marital_status, children, car, area,
                           house, credentials_type, credentials_num, monthly_income, annual_income, flag) {
    var url = "/Lvscore_User_M/account/ajaxUpdateDetails";
    $.post(url, {
        'real_name': real_name,
        'sex': sex,
        'birth': birth,
        'education': education,
        'marital_status': marital_status,
        'children': children,
        'car': car,
        'area': area,
        'house': house,
        'credentials_type': credentials_type,
        'credentials_num': credentials_num,
        'monthly_income': monthly_income,
        'annual_income': annual_income
    }, function (data) {
        if (data == '1') {
            alertBox("修改成功");
            if (flag == 1) {
                location.reload();
            }
        } else if (data == '-1')
            alertBox("修改失败", '');
        else
            alertBox("服务器异常", '');
    }, "json");
}

/**
 * 更新用户广告类型
 *
 * @param ad_category
 *            (用户修改的广告类型 ad_category)
 */
function ajaxUpdateCategory(ad_category) {
    var url = "/Lvscore_User_M/account/ajaxUpdateCategory";
    $.post(url, {
        'ad_category': ad_category
    }, function (data) {
        if (data == '1')
            alertBox("修改成功");
        else if (data == '-1')
            alertBox("修改失败", '');
        else
            alertBox("服务器异常", '');
    }, "json");
}

/**
 * 更新用户广告分类关键字
 *
 * @param ad_key
 *            (用户修改的广告分类关键字 ad_key)
 */
function ajaxUpdateAd_key(ad_key) {
    var url = "/Lvscore_User_M/account/ajaxUpdateAd_key";
    $.post(url, {
        'ad_key': ad_key
    }, function (data) {
        if (data == '1')
            alertBox("修改成功");
        else if (data == '-1')
            alertBox("修改失败", '');
        else
            alertBox("服务器异常", '');
    }, "json");
}

/**
 * 更新用户兴趣爱好
 *
 * @param hobby
 *            (用户修改的兴趣爱好 hobby)
 */
function ajaxUpdateHobby(hobby) {
    var url = "/Lvscore_User_M/account/ajaxUpdateHobby";
    $.post(url, {
        'hobby': hobby
    }, function (data) {
        if (data == '1')
            alertBox("修改成功");
        else if (data == '-1')
            alertBox("修改失败", '');
        else
            alertBox("服务器异常", '');
    }, "json");
}

/**
 * 新用户绑定邮箱获取验证码
 *
 * @param mail
 *            (用户新绑定的邮箱号码 mail)
 */
function ajaxGetCodeByNewMail(mail, that) {
    var url = "/Lvscore_User_M/account/ajaxGetCodeByNewMail";
    $.post(url, {
        'mail': mail
    }, function (data) {
        /**
         * "0"：服务器异常 发送失败 "-1"：发送成功 "1"：该邮箱已被注册
         */
        that.disabled = false;
        if (data == '1') {
            alertBox("发送成功，请注意查收");
        } else if (data == '-1') {
            alertBox("该邮箱已被注册", '');
        } else {
            alertBox("发送失败，服务器异常", '');
        }
        settime(that);
    }, "json");
}

/**
 * 验证新邮箱的验证码是否正确
 * code    用户输入的验证码
 */
function ajaxValidateCodeNewMail(that, mail, code) {
    var url = "/Lvscore_User_M/account/ajaxValidateCodeNewMail";
    $.post(
        url,
        {
            mail: mail,
            code: code
        },
        function (data) {
            if (data == '1') {
                ajaxSaveNewMail(that, $("[name = 'mail']").val());
            } else {
                that.disabled = false;
                alertBox("验证码错误", '');
            }
        },
        "json"
    );
}

/**
 * 更新邮箱
 * mail    用户输入的新邮箱
 */
function ajaxSaveNewMail(that, mail) {
    var url = "/Lvscore_User_M/account/ajaxSaveNewMail";
    $.post(
        url,
        {'mail': mail},
        function (data) {
            that.disabled = false;
            if (data == '1')
                location.reload();
            else if (data == '-1') {
                alertBox("邮箱绑定失败", '');
            } else {
                alertBox("服务器异常，绑定失败", '');
            }
        },
        "json"
    );
}

